﻿<template>
    <div class="esProductChannel-container">
        <el-dialog v-model="state.isShowDialog" draggable width="769px">
            <template #header>
                <div style="color: #fff">
                    <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
                        <ele-Edit/>
                    </el-icon>
                    <span> {{ props.title }} </span>
                </div>
            </template>
            <el-form :model="state.ruleForm" ref="ruleFormRef" size="default" label-width="80px" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="产品名称" prop="productId">
                            <el-select v-model="state.selectedProduct" filterable placeholder="请选择" class="w100"
                                       :disabled='props.title=="编辑"'>
                                <el-option v-for='item in state.productDict' :key='item.value' :label='item.label'
                                           :value='item' @click.native="selectProduct(item)"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="渠道名称" prop="channelId">
                            <el-select v-model="state.selectedChannel" filterable placeholder="请选择" class="w100"
                                       :disabled='props.title=="编辑"'>
                                <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                           :value='item' @click.native="selectChannel()"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="Key" prop="code">
                            <el-text class="w100" type="primary"
                                     style="text-align: center; border-radius: 4px; border: 1px solid var(--el-border-color)">
                                {{ state.ruleForm.code }}
                            </el-text>
                            <!--							<el-input v-model="state.ruleForm.code" placeholder="请输入Key" class="w100" clearable />-->
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="商户价格" prop="merchantSettlementPrice"
                                      :rules="[{ required: true, type: 'number', message: '商户价格不能为空', trigger: 'blur' }]">
                            <el-input-number v-model="state.ruleForm.merchantSettlementPrice" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入商户价格" class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="渠道价格" prop="channelSettlementPrice"
                                      :rules="[{ required: true, type: 'number', message: '渠道价格不能为空', trigger: 'blur' }]">
                            <el-input-number v-model="state.ruleForm.channelSettlementPrice" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入渠道价格" class="w100"/>
                        </el-form-item>
                    </el-col>
<!--                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--                        <el-form-item label="时限数量" prop="hourlyLimit">-->
<!--                            <el-input-number v-model="state.ruleForm.hourlyLimit" :min="0" :max="9999"-->
<!--                                             controls-position="right" placeholder="请输入小时限数量" class="w100"/>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->
<!--                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--                        <el-form-item label="日限数量" prop="dailyLimit">-->
<!--                            <el-input-number v-model="state.ruleForm.dailyLimit" :min="0" :max="9999"-->
<!--                                             controls-position="right" placeholder="请输入日限数量" class="w100"/>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->
<!--                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--                        <el-form-item label="月限数量" prop="monthlyLimit">-->
<!--                            <el-input-number v-model="state.ruleForm.monthlyLimit" :min="0" :max="9999"-->
<!--                                             controls-position="right" placeholder="请输入月限数量" class="w100"/>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="扣量 自" prop="startingQuantity">
                            <el-input-number v-model="state.ruleForm.startingQuantity" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入扣量起始数量" class="w100"/>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
                        <el-form-item label="后，每" label-width="70px" prop="deductionInterval">
                            <el-input-number v-model="state.ruleForm.deductionInterval" :min="0" :max="20"
                                             controls-position="right" placeholder="请输入扣量间隔数量" class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
                        <el-form-item label="扣" label-width="10px" prop="deductionNumerator">
                            <el-input-number v-model="state.ruleForm.deductionNumerator"
                                             :min="(state.ruleForm.deductionInterval || 0)*-1"
                                             :max="state.ruleForm.deductionInterval"
                                             controls-position="right" placeholder="请输入扣量间隔数量" class="w60"/>
                            <el-text class="w40" type="success" style="text-align: right; ">
                                ≈
                                {{
                                    state.ruleForm.deductionInterval == 0 ? 0 : ((Math.abs(state.ruleForm?.deductionNumerator || 0) / (state.ruleForm?.deductionInterval || 1) * 1.0) * 100.00).toFixed(0)
                                }}%
                            </el-text>
                        </el-form-item>
                    </el-col>
                    <!--					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">-->
                    <!--						<el-form-item label="克隆代码">-->
                    <!--							<el-select v-model.trim="state.ruleForm.FromCloneProductChannelId" value-key="value"-->
                    <!--									placeholder="会复制该产品第一次的开通省份、推广时间等配置" class="w100" filterable :disabled='props.title=="编辑"' >-->
                    <!--								<el-option v-for='item in state.productChannelDict' :key='item.value' :label='item.label'-->
                    <!--									:value='item.value' />-->
                    <!--							</el-select>-->
                    <!--						</el-form-item>-->
                    <!--					</el-col>-->
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="配置状态" prop="status">
                            <el-select v-model="state.ruleForm.status" placeholder="请选择" class="w100">
                                <el-option label="启用" :value="1"></el-option>
                                <el-option label="停用" :value="2" :disabled="true"></el-option>
                                <el-option label="到量" :value="3"></el-option>
                                <el-option label="短期关停" :value="4"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="间隔同步" prop="intervalSyncPeriod">
                            <el-input-number v-model="state.ruleForm.intervalSyncPeriod" :min="0" :max="9999"
                                             controls-position="right" placeholder="请输入间隔同步周期（单位：秒）"
                                             class="w100"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="同步类型" prop="syncOnlySuccess">
                            <el-select v-model="state.ruleForm.syncOnlySuccess" placeholder="请选择是否仅同步成功"
                                       class="w100">
                                <el-option label="成功数据" :value="1"></el-option>
                                <el-option label="全部数据" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="APP黑单">
                            <el-radio-group v-model="state.ruleForm.blackApp" class="ml-4">
                                <el-radio
                                    v-for="item in optionDict.YesNoDict"
                                    :key="item.value"
                                    :label="item.value"
                                >
                                    {{ item.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="同步链接" prop="syncUrl">
                            <el-input v-model="state.ruleForm.syncUrl" placeholder="默认使用上次的同步链接" class="w100"
                                      clearable
                                      type="textarea" maxlength="300" style="word-break: break-all;"
                                      :autosize="{ minRows: 2 }"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="IP限制">
                            <el-radio-group v-model="state.ruleForm.isLimitIP" class="ml-4">
                                <el-radio
                                    v-for="item in optionDict.YesNoDict"
                                    :key="item.value"
                                    :label="item.value"
                                >
                                    {{ item.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="业务互斥">
                            <el-radio-group v-model="state.ruleForm.isMutex" class="ml-4">
                                <el-radio
                                    v-for="item in optionDict.YesNoDict"
                                    :key="item.value"
                                    :label="item.value"
                                >
                                    {{ item.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="大Key" prop="categoryCode">
                            <el-input v-model="state.ruleForm.productCategoryCode"
                                      controls-position="right" placeholder="大Key" class="w100" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="同品排序" prop="categoryIndex">
                            <el-input-number v-model="state.ruleForm.productCategoryIndex" :min="0" :max="99"
                                             controls-position="right" placeholder="同品排序" class="w100" />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="备注">
                            <el-input v-model="state.ruleForm.remark" placeholder="请输入备注内容" clearable
                                      type="textarea"
                                      maxlength="255" style="word-break: break-all;" :autosize="{ minRows: 2 }"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel" size="default">取 消</el-button>
					<el-button type="primary" @click="submit" size="default">确 定</el-button>
				</span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="editEsProductChannel">

import {reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import type {FormRules} from "element-plus";
import mittBus from '/@/utils/mitt';

import {EsProductChannel, sysBaseDict} from '/@/api/models';
import SysEsProductChannelApi from '/@/api/exocytosis/productChannel';
import SysEsProductApi from '/@/api/exocytosis/product';
import SysEsChannelApi from '/@/api/exocytosis/channel';
import commonFunction from '/@/utils/commonFunction';
import {optionDict} from "/@/const/dict";

// 定义变量内容
const {generateRandomLowercaseString} = commonFunction();
const props = defineProps({
    title: String,
});

const ruleFormRef = ref();
const state = reactive({
    isShowDialog: false,
    productDict: [] as sysBaseDict[],
    channelDict: [] as sysBaseDict[],
    // productChannelDict: [] as sysBaseDict[],
    selectedProduct: {} as sysBaseDict,
    selectedChannel: {} as sysBaseDict,
    ruleForm: {} as EsProductChannel,
});

// 删除非必填规则
const rules = ref<FormRules>({
    productId: [{required: true, message: '请输入产品Id！', trigger: 'blur',},],
    channelId: [{required: true, message: '请输入渠道Id！', trigger: 'blur',},],
    status: [{required: true, message: '请输入配置状态！', trigger: 'blur',},],
    merchantSettlementPrice: [{required: true, message: '请输入商户结算价格！', trigger: 'blur',},
        {
            pattern: /^\d+$/,
            message: '商户结算价格单位是分，必须是整数！',
            trigger: 'blur'
        }
    ],
    channelSettlementPrice: [{required: true, message: '请输入渠道结算价格！', trigger: 'blur',},
        {
            pattern: /^\d+$/,
            message: '渠道结算价格单位是分，必须是整数！',
            trigger: 'blur'
        }
    ],
    hourlyLimit: [{required: true, message: '请输入小时限数量！', trigger: 'blur',},],
    dailyLimit: [{required: true, message: '请输入日限数量！', trigger: 'blur',},],
    monthlyLimit: [{required: true, message: '请输入月限数量！', trigger: 'blur',},],
    startingQuantity: [{required: true, message: '请输入扣量起始数量！', trigger: 'blur',},],
    deductionInterval: [{required: true, message: '请输入扣量间隔数量！', trigger: 'blur',},],
    deductionNumerator: [{required: true, message: '请输入扣量数量！', trigger: 'blur',},],
    isMutex: [{required: true, message: '请输入是否开启业务互斥！', trigger: 'blur',},],
});

// 打开弹窗
const openDialog = async (row: EsProductChannel, condition: string) => {
    // 渠道字典
    await channelQuery();
    // 产品字典
    await productQuery();
    state.selectedProduct = state.productDict.find((item) => {
        return item.value === row.productId;
    }) ?? null;
    state.selectedChannel = state.channelDict.find((item) => {
        return item.value === row.channelId;
    }) ?? null;
    if (condition == 'add') {
        state.ruleForm = row;
        state.isShowDialog = true;
        state.ruleForm.code = generateRandomLowercaseString(6);
    } else {
        state.ruleForm = row;
        state.isShowDialog = true;
    }
};

// 关闭弹窗
const closeDialog = () => {
    mittBus.emit('submitRefresh');
    state.isShowDialog = false;
};

// 取消
const cancel = () => {
    state.isShowDialog = false;
};

// 提交
const submit = () => {
    state.ruleForm.productId = state.selectedProduct?.value;
    state.ruleForm.channelId = state.selectedChannel?.value;
    state.ruleForm.operatorPlatform = state.selectedProduct?.exValue;
    state.ruleForm.merchantId = state.selectedProduct?.exValueData;
    ruleFormRef.value.validate(async (valid: boolean, fields?: any) => {
        if (valid) {
            let res;
            if (state.ruleForm.id) {
                res = await SysEsProductChannelApi().editPost(state.ruleForm);
            } else {
                res = await SysEsProductChannelApi().addPost(state.ruleForm);
            }
            if (res.data.resCode != '0000')
                ElMessage.error(res.data.resMessage);
            else {
                ElMessage.success("操作成功");
                closeDialog();
            }
        } else {
            ElMessage({
                message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
                type: "error",
            });
        }
    });
};

// 渠道字典
const channelQuery = async () => {
    await SysEsChannelApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};

// 产品字典
const productQuery = async () => {
    await SysEsProductApi().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.productDict = res.data.result ?? [];
    });
};

// 产品渠道字典
// const productChannelQuery = async (val: string) => {
// 	await SysEsProductChannelApi().queryAll({productId: val}).then((res) => {
// 		if (res.data.resCode === '0000')
// 			state.productChannelDict = res.data.result ?? [];
// 	});
// };

// 选择产品
const selectProduct = async (item: any) => {
    // state.ruleForm.FromCloneProductChannelId = undefined;
    // // 产品渠道字典
    // productChannelQuery(item.value);

    state.ruleForm.code = (state.selectedChannel?.exValue?.toString() ?? '') +
        (state.selectedProduct?.index?.toString().padStart(3, '0') ?? '000');
    state.ruleForm.merchantSettlementPrice = item.incomePrice;
}

// 选择渠道
const selectChannel = async () => {
    state.ruleForm.code = (state.selectedChannel?.exValue?.toString() ?? '') +
        (state.selectedProduct?.index?.toString().padStart(3, '0') ?? '000');
}

// 导出对象 将属性或者函数暴露给父组件
defineExpose({openDialog});
</script>
